package cn.hj.pet.service.impl;

import cn.hj.basic.service.impl.BaseServiceImpl;
import cn.hj.pet.domain.Pet;
import cn.hj.pet.domain.PetDetail;
import cn.hj.pet.mapper.PetDetailMapper;
import cn.hj.pet.mapper.PetMapper;
import cn.hj.pet.service.IPetService;
import cn.hj.user.domain.Logininfo;
import cn.hj.user.domain.User;
import cn.hj.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class PetServiceImpl  extends BaseServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Autowired
    private UserMapper userMapper;


    /**
     * 保存pet数据和PetDetail数据
     * @param pet
     */
    @Override
    @Transactional
    public void add(Pet pet) {
        //保存pet数据返回id
        petMapper.insert(pet);

        PetDetail detail = pet.getDetail();
        detail.setPet_id(pet.getId());
        //保存pet数据返回idPetDetail数据
        petDetailMapper.insert(detail);
    }


    /**
     * 上架宠物
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public void onSale(List<Long> ids) {
        HashMap<String, Object> map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh-MM-ss");
        map.put("onsaleTime",format.format(new Date()));
        map.put("ids",ids);
        petMapper.onSale(map);
    }

    /**
     * 下架宠物
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public void offSale(List<Long> ids) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("offsaleTime",new Date());
        map.put("ids",ids);
        petMapper.offSale(map);
    }


    /**
     * 查询宠物信息加详情
     * @param id
     * @return
     */
    @Override
    public Pet fandById(Long id) {
       return petMapper.loadByIdDetail(id);
    }

    /**
     * 领养宠物
     * @param id
     */
    @Override
    @Transactional
    public void adopt(Long id, Logininfo logininfo) {
        //下架宠物
        Pet pet = petMapper.selectById(id);
        pet.setState(0);
        pet.setOffsaletime(new Date());
        //绑定宠物领养人
        User user = userMapper.getByLogInfoId(logininfo.getId());
        pet.setUser_id(user.getId());
        petMapper.update(pet);
        //生成订单@todo
    }
}
